// pages/home/home.js
const GoodsListUrl = '/Goods/index';
const upDateAdvUrl = '/GlobalConfig/getCateAdv';
const activityInfoUrl = '/Activity/index';
const shareSuccessUrl = '/Activity/jumpSuccess';
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isfriendShareMaskShow:0,//控制赠送优惠券弹层的显示
    isLoading:0,//是否已经调完接口0没有1已经调完
    share_image:'',//分享图
    share_page: '',//分享路径
    share_title: '',//分享标题
    user_status: '',//1分包邮的用户状态
    activity_image: '',//1分领顶部图片
    represent: '',//【1分钱包邮】正品韩束面膜  景甜代言
    share_btn_title: '',//再分享1个群或好友立即领取
    share_success_btn_title: '',//前往领取
    get_success_title: '',//已经成功领取
    get_success_two_title: '',//可前往我的订单查看哦
    get_success_btn_title: '',//去查看我的订单
    share_friend_btn_title: '',//发给朋友一起领
    invite_btn_title: '',//生成邀请图片
    activity_time_title: '',//限时活动
    activity_title: '',//分享后每位新用户领取面膜，奖励
    activity_award_money: 0,//1
    activity_award_unit: '',//元
    programPage: '',
    programApp_id: '',
    isOnesubpackageMask:0,//是否显示1分包邮弹层
    cate_id:0,//当前商品分类的ID
    two_cate_id:0,//当前商品子分类的ID
    adv_info:'',//首页导航列表数据
    isGetInfo:0,//判断用户是否已经授权
    sys_status:"0",//当前小程序的状态
    displayAuthShow: 0,//控制授权弹层的显示和隐藏
    winHeight: "",//窗口高度
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    carousel_is_show: 1,//控制头部轮播图片的显示和隐藏
    category:[],//存储商品类型列表
    goodslist: [],//商品列表
    page: 1,//初始化商品列表页码
    filesSourceUri: '',//普通资源文件地址
    localSourceUri:'',//本地资源文件
    carousel_adv_info: [],//轮播图列表
  },
  // 跳转我的现金券页面
  goCouponList: function () {
    this.setData({
      isfriendShareMaskShow: 0
    })
    wx.navigateTo({
      url: '/pages/couponList/couponList',
    })
  },
  // 关闭好友分享成功弹层
  closefriendShareMask: function () {
    var _this = this;
    _this.setData({
      isfriendShareMaskShow: 0
    });
  },
  // 关闭1分包邮弹层
  closeOnesubpackageMask:function(){
    this.setData({
      isOnesubpackageMask:0
    })
  },
  // 生成邀请图片
  getShareImg:function(e){
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    wx.navigateTo({
      url: '/pages/getShareImg/getShareImg?activity_time_title=' + _this.data.activity_time_title + '&activity_title=' + _this.data.activity_title + '&activity_award_money=' + _this.data.activity_award_money + '&activity_award_unit=' + _this.data.activity_award_unit,
    })
  },
  // 跳转其他小程序
  goOtherProgram:function(e){
    var _this = this;
    var share_type = e.currentTarget.dataset.type;
    wx.navigateToMiniProgram({
      appId: _this.data.programApp_id.toString(),
      path: _this.data.programPage.toString(),
      envVersion: 'develop',
      complete(res) {
      },
      success(res){
        _this.shareSuccess(share_type);
      }
    });
  },
  // 跳转首页
  goHome: function () {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  // 跳转购物车
  goBuyCar: function () {
    wx.reLaunch({
      url: '/pages/buyCar/buyCar',
    })
  },
  // 跳转搜索
  goSearch: function () {
    wx.reLaunch({
      url: '/pages/search/index',
    })
  },
  // 跳转我的
  goMy: function () {
    wx.reLaunch({
      url: '/pages/my/my',
    })
  },
  // 滚动切换标签样式
  switchTab: function (e) {
    var category = this.data.category;
    var cate_id = category[e.detail.current].id;
    this.setData({
      isLoading: 0,
      two_cate_id:0,
      cate_id: cate_id,
      goodslist:[],
      currentTab: e.detail.current,
      page:1
    });
    this.checkCor();
    this.getGoodsList();
    this.upDateAdv();
  },
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
     var cate_id = e.currentTarget.dataset.cate_id;
    if ((typeof e.currentTarget.dataset.current)=='number'){
      var cur = e.currentTarget.dataset.current;
      if (this.data.currentTab == cur) { return false; }
      else {
          this.setData({
            isLoading:0,
            cate_id: cate_id,
            goodslist: [],
            two_cate_id:0,
            currentTab: cur
          })
      }
    }else{
      this.setData({
        cate_id: e.currentTarget.dataset.cate_id,
        two_cate_id: e.currentTarget.dataset.two_cate_id,
        goodslist: [],
        page:1
      })
      this.getGoodsList();
    }
  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    if (this.data.currentTab > 3) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  // 更新轮播图和下方广告位
  upDateAdv:function(e){
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      cate_id: _this.data.cate_id
    }
    app.post(upDateAdvUrl, requestData, function (res) {
      if (res.code == 2000) {
        _this.setData({
          adv_info:res.data.adv_info,
          carousel_adv_info: res.data.carousel_adv_info
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 免费领按钮
  freeReceive: function (e) {
    var _this = this;
    var theGoodsId = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + theGoodsId,
    })
  },
  // 获取1分包邮弹层信息
  getActivityInfo:function(){
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type
    }
    app.post(activityInfoUrl, requestData, function (res) {
      if (res.code == 2000) {
        _this.setData({
          share_image: res.data.share_image,
          share_page: res.data.share_page,
          share_title: res.data.share_title,
          user_status: res.data.user_status,
          activity_image: _this.data.filesSourceUri+'/'+res.data.image,//1分领顶部图片
          represent: res.data.represent,//【1分钱包邮】正品韩束面膜  景甜代言
          share_btn_title: res.data.share_btn_title,//再分享1个群或好友立即领取
          share_success_btn_title: res.data.share_success_btn_title,//前往领取
          get_success_title: res.data.get_success_title,//已经成功领取
          get_success_two_title: res.data.get_success_two_title,//可前往我的订单查看哦
          get_success_btn_title: res.data.get_success_btn_title,//去查看我的订单
          share_friend_btn_title: res.data.share_friend_btn_title,//发给朋友一起领
          invite_btn_title: res.data.invite_btn_title,//生成邀请图片
          activity_time_title: res.data.activity_time_title,//限时活动
          activity_title: res.data.activity_title,//分享后每位新用户领取面膜，奖励
          activity_award_money: Math.ceil(res.data.activity_award_money),//1
          activity_award_unit: res.data.activity_award_unit,//元
          programPage: res.data.page,
          programApp_id: res.data.app_id
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 分享成功的接口
  shareSuccess:function(e){
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      share_type:e
    }
    app.post(shareSuccessUrl, requestData, function (res) {
      if (res.code == 2000) {
        _this.setData({
          user_status: res.data.user_status
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    })
  },
  // 获取商品列表接口
  getGoodsList: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      cate_id: _this.data.cate_id,
      two_cate_id: _this.data.two_cate_id,
      page: _this.data.page
    }
    app.post(GoodsListUrl, requestData, function (res) {
      if (res.code == 2000) {
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
        var goodslist = _this.data.goodslist;
        goodslist = goodslist.concat(res.data.list);
        _this.setData({
          isLoading:1,
          page: res.data.page,
          goodslist: goodslist
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  text:function(){
    var requestData = {
      token: this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type
    }
    app.post('/Help/test', requestData, function (res) {
      if (res.code == 2000) {
        wx.hideLoading();
        var payInfo = res.data;
        if (payInfo.respay) {
          wx.requestPayment({
            'timeStamp': payInfo.respay.timeStamp,
            'nonceStr': payInfo.respay.nonceStr,
            'package': payInfo.respay.package,
            'signType': 'MD5',
            'paySign': payInfo.respay.paySign,
            'success': function (res) {
              // _this.getPageInfo();
              _this.setData({
                isWithdrawalsSuccessShow: 1,
                isAdding: true
              })
              wx.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 1500
              })
            },
            'fail': function (res) {
              // _this.getPageInfo();
              _this.setData({
                isAdding: false
              })
            },
            'complete': function (res) {
              _this.getPageInfo();
            }
          });
        } else {
          _this.getPageInfo();
          _this.setData({
            isAdding: true,
            isWithdrawalsSuccessShow: 1
          })
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500
          })
        }

      } else {
        _this.setData({
          isAdding: false
        })
        wx.hideLoading();
        wx.showToast({
          title: res.msg,
          icon: 'loading',
          mask: true,
          duration: 1500
        });
      }
    })
  },
  /*角色权限控制*/
  getUserInfo: function (e) {
    var that = this;
    var infoUser = e.detail.userInfo;
    var res = e.detail;
    var url = app.setConfig.url + '/Login/doLogin';
    that.setData({
      displayAuthShow: 0,
      isGetInfo: 1
    });
    var data = {
      user_name: infoUser.nickName,
      nick_name: infoUser.nickName,
      head_img: infoUser.avatarUrl,
      sex: infoUser.gender,
      coutry: infoUser.country,
      city: infoUser.city,
      province: infoUser.province,
      code: app.globalData.code,
      encryptedData: res.encryptedData,
      signature: res.signature,
      ctype: app.setConfig.type,
      version: app.setConfig.version,
      iv: res.iv,
    }
    app.postLogin(url, data, function () {
      var cash = wx.getStorageSync('cash');
      if (cash != "") {
        that.setData({
          displayAuthShow:0,
          isfriendShareMaskShow: 1,
          cash:cash
        })
      }
      that.loop();
      that.isGetInitConfig();
      wx.navigateBack({
        delta:1,
      })
    });
  },
  authRest: function () {
    this.setData({
      displayAuthShow: 0
    });
    setTimeout(function () {
      wx.reLaunch({
        url: '/pages/home/home',
      })
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    // console.log(options);
    var isOnesubpackageMask = 0;
    app.checkAuthioze(success => {
      var configs = wx.getStorageSync('configs');
      var category = wx.getStorageSync('category');
      var carousel_adv_info = wx.getStorageSync('carousel_adv_info');
      var adv_info = wx.getStorageSync('adv_info');
      var adv_solt = wx.getStorageSync('adv_solt');
      var static_url = wx.getStorageSync('static_url');
      var scene = decodeURIComponent(options.scene);
      if (scene && scene !== 'undefined') {
        console.log(1);
        var sceneParams = new Array();
        sceneParams = scene.split('#');
        if (sceneParams[0] == "postage") {
          console.log(1);
          isOnesubpackageMask = 1;
        } else {
          isOnesubpackageMask = 0;
          console.log(0);
        }
      }else{
        if (options.activity == 'postage') {
          isOnesubpackageMask = 1;
        } else {
          isOnesubpackageMask = 0;
        }
      }
      if (options.id) {
        _this.setData({
          isOnesubpackageMask: isOnesubpackageMask,
          currentTab:options.id,
          cate_id: options.cate_id
        })
      } else {
        _this.setData({
          isOnesubpackageMask: isOnesubpackageMask
        })
      }
      _this.loop();
      _this.isGetInitConfig();
    }, fail => {
     /*var pages = getCurrentPages();
      var prevpage = pages[pages.length - 2]; 
      console.log(prevpage);
       if (options.is_authorization){
        if (prevpage.route){
        if (options.is_authorization == 1 && prevpage.route == 'pages/home/home'){
          wx.navigateBack({
            data:1
          })
        }
      }
   }*/
      //未授权提示用户授权
      _this.setData({
        displayAuthShow: 1
      });
    });
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth;
        _this.setData({
          winWidth: res.windowWidth,
          winHeight: clientHeight
        })
      }
    });
    _this.checkCor();
  },
  // 判断是否获取到本地缓存了
  isGetInitConfig:function(){
    var _this = this;
    var initConfig = wx.getStorageSync("initConfig");
    if (!initConfig) {
      setTimeout(function () { _this.isGetInitConfig() }, 100);
    } else {
      _this.setData({
        category: initConfig.category,
        adv_solt: initConfig.adv_solt,
        sourceUri: initConfig.static_url,
        filesSourceUri: initConfig.configs.static_url_http,
        localSourceUri: initConfig.configs.static_url_http,
        sys_status: initConfig.configs.sys_status
      })
    }
  },
  // 判断是否获取到token的值了
  loop: function () {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    if (!theToken) {
      setTimeout(function () { _this.loop() }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      if (_this.data.isGetInfo==1){
      }
      _this.getGoodsList();
      _this.upDateAdv();
      // _this.text();
      if (_this.data.isOnesubpackageMask==1){
        _this.getActivityInfo();
      }
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // wx.navigateBack({
    //   data:1
    // })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var _this = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    _this.setData({
      goodslist: [],//存储首页书籍列表
      page: 1
    })
    _this.getGoodsList();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var _this = this;
    _this.getGoodsList();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var _this = this;
    var buttonType = e.target.dataset.type;
    _this.shareSuccess(buttonType);
    var title = _this.data.share_title;
    var path = _this.data.share_page;
    var share_image = _this.data.localSourceUri+_this.data.share_image;
    return {
      title: title,
      path: path,
      imageUrl: share_image,
      success: function (res) {
        wx.showToast({
          title: '分享成功',
          duration: 2000,
          icon: "none"
        })
      },
    }
  },
  // 点击顶部导航跳转广告详情
  jumpDetail: function (e) {
    var advType = e.currentTarget.dataset.type_detail;
    var subject_id = advType.adv_id;
    if (advType.adv_type == 3) {
      wx.navigateToMiniProgram({
        appId: 'wx6d9f6c9ecdd43db9',
        envVersion: 'develop',
        complete(res) {
          console.log(res)
        }
      });
    } else if (advType.adv_type == 4) {
      wx.navigateTo({
        url: '/' + advType.adv_uri + '?subject_id=' + subject_id,
      })
    }
  },
  /*红包广告跳转事件*/
  goAdvEvent: function (e) {
    var _this = this;
    var adv_solt = _this.data.adv_solt;
    if (_this.data.adv_solt) {
      //广告数据不为空
      if (adv_solt.adv_type == 1) {
        //图片类
        wx.navigateTo({
          url: '/pages/rule/rule?url=' + adv_solt.adv_info_url
        });
      } else if (adv_solt.adv_type == 3) {
        //小程序类
        wx.navigateToMiniProgram({
          appId: adv_solt.app_id.toString(),
          path: adv_solt.page.toString(),
          extraData: adv_solt.sence.toString(),
          complete(res) {
          }
        });
      } else {
        //内部网页类型
        wx.navigateTo({
          url: "/" + adv_solt.adv_uri,
        })
      }
    }
  },
  // 顶部机器人轮播结束执行的函数
  animationfinish: function () {
  }
})